<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const user = reactive({
  title: ''
})
// ----
const fold = reactive({
  count: 2,
  height: 0,
  info: ''
})
// --mescroll--
const noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const layer = ref()

/* ---- */
const setAppTitle = (title) => {
  document.title = title
  // --利用iframe的onload事件刷新页面--
  const iframe = document.createElement('iframe')
  iframe.style.visibility = 'hidden'
  iframe.style.width = 0
  iframe.style.height = 0
  document.body.appendChild(iframe)
  nextTick(() => { document.body.removeChild(iframe) })
}
// ----
const getCurrencyInfo = async (callback) => {
  fold.height = proxy.$refs.forTrueHeight.offsetHeight
  // --获取合作商家分类信息--
  const forCateData = { params: { 'CommonTypeSearch[id]': proxy.$route.query.id } }
  await proxy.$Axios.all([
    proxy.$Axios.get('common-type/index', forCateData)
  ]).then(proxy.$Axios.spread((cateData) => {
    const CData = cateData.items[0] || {}
    user.title = proxy.$Myfun.setText(CData.name)
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // --设置网页title--
  const forTitle = user.title || document.title
  setAppTitle(forTitle)
  // ----
  callback && callback()
}
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 15 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 10,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  getListDataFromNet({
    forUrl: 'program/index',
    forData: {
      params: {
        'ProgramSearch[common_type_id]': proxy.$route.query.id,
        // --打开推广属性--
        'ProgramSearch[is_extension]': 1,
        // ----
        page: page.num,
        PageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const getFoldState = () => {
  return new Promise((resolve, reject) => {
    nextTick(() => {
      const curFoldH = proxy.$refs.forTrueHeight.offsetHeight
      if (Number(curFoldH / fold.height) > Number(fold.count)) {
        resolve(true)
      } else {
        resolve(false)
      }
    })
  })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    let forFold = false
    let forDesc = ''
    await proxy.$Myfun.getJsonData(item.description, (resJson) => {
      if (resJson[0].remark) forDesc = proxy.$Myfun.setText(resJson[0].remark)
    })
    fold.info = '销售佣金：' + forDesc
    await getFoldState().then((result) => { forFold = result })
    // ----
    let forImg = ''
    proxy.$Myfun.getJsonData(item.icon, (resJson) => {
      if (Number(resJson.length) > 0) forImg = resJson[0].image
    })
    // ----
    newItems.push({
      id: item.id,
      name: proxy.$Myfun.setText(item.name),
      remark: forDesc,
      // ----
      image: forImg,
      // ----
      isFold: forFold
    })
    // ----
    fold.info = ''
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      proxy.$Myfun.openPage(proxy, 'push', 'PromoteShare', { id: item.id })
      break
    }
  }
}

/* ---- */
onMounted(() => {
  getCurrencyInfo(() => {
    // --创建MeScroll对象--
    setTimeout(() => { startMeScroll() }, 500)
  })
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => { if (mescroll) mescroll.destroy() })
</script>

<template>
  <div>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <ul class="list-push xw-flex xw-flex-column" ref="dataList">
          <li class="xw-bg-white xw-Tfg" v-for="(item, index) in items"><a class="xw-flex">
            <div class="LPH-img xw-radius-3" @click="getAuditFun(1, item)" v-if="item.image"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.image + ')' }"></div></div>
            <div class="LPH-con xw-flex-W1">
              <div class="LPH-title xw-ellipsis" @click="getAuditFun(1, item)">{{item.name}}</div>
              <div class="LPH-desc xw-color-13 xw-flex" v-if="item.remark">
                <input type="checkbox" :id="'check_' + index" class="xw-fold-handle">
                <div class="xw-fold-text">
                  <div class="xw-fold-abs" @click="getAuditFun(1, item)"></div>
                  <label class="xw-fold-btn" :for="'check_' + index" v-if="item.isFold"></label>
                  <span class="xw-color-11">销售佣金：</span>{{item.remark}}
                </div>
              </div>
            </div>
          </a></li>
          <div class="list-li list-li-fold"><div ref="forTrueHeight">{{fold.info}}</div></div>
        </ul>
      </div>
    </div>
    <sliding-view ref="sliding"/>
    <layer-view ref="layer"/>
  </div>
</template>

<style scoped>
/* ---- */
.xw-fold-text { max-height: 4rem; }

/* ---- */
.list-push li a { padding: 1.2rem 1rem; }
.list-push li:before { left: 9rem; right: 1rem; }
.list-push li:nth-of-type(1):before { display: none; }
.LPH-img { margin-right: 1rem; width: 7rem; height: 7rem; }
.LPH-title { line-height: 3rem; font-size: 1.7rem; }
.LPH-desc div { text-align: justify; }
.list-li-fold { padding: 0 1rem 0 9rem; }
.list-li-fold div { min-height: 2rem; line-height: 2rem; text-align: justify; }
</style>